﻿var zombies = zombies || {};

zombies.ListProduct = function () {
    var self = this;
    self.Products = ko.observableArray();
    self.SearchString = ko.observable("");
    self.CurrentPage = ko.observable(1);
    self.IsPrevious = ko.observable(false);
    self.IsNext = ko.observable(false);
    self.Loaded = ko.observable(false);

    self.SendMsg = function (data, event) {
        try {
            if (event.which === 13) {
                self.CurrentPage(1);
                load(self.CurrentPage(), self.SearchString());
                $.replaceUrl(self.CurrentPage(), self.SearchString());
                return false;
            }
            return true;
        }
        catch (e)
        { }

    };

    self.PId = ko.observable();
    self.Name = ko.observable();
    self.Description = ko.observable();
    self.Score = ko.observable();
    self.ProductImg = ko.observable();
    self.Quantity = ko.observable();

    self.itemTodel = ko.observable();

    self.getEditItem = function (item) {
        self.PId(item.PId);
        self.Name(item.Name);
        CKEDITOR.instances['val_des'].setData(item.Description);
        self.Score(item.Score);
        self.ProductImg(item.ProductImg);
        self.Quantity(item.Quantity);
    }


    self.doEdit = function (formElement) {
        console.log("a");
        var product = ko.utils.arrayFirst(self.Products(), function (item) {
            return item.PId === self.PId();
        });
        self.ProductData = ko.observable({
            PId: self.PId,
            Name: self.Name,
            Score: self.Score,
            ProductImg: self.ProductImg,
            Quantity: self.Quantity,
            Description: CKEDITOR.instances['val_des'].getData()
        });
        console.log(ko.toJSON(self.ProductData()));

        $.ajax({
            type: "PUT",
            url: "/api/AdminProduct/PutProduct",
            data: ko.toJSON(self.ProductData()), //Convert the Observable Data into JSON
            contentType: "application/json",
            dataType: 'json'
        }).done(function () {
            toastr.success('Edit Product Successfully !');
            self.Products.replace(product, { PId: self.PId(), Name: self.Name(), Description: CKEDITOR.instances['val_des'].getData(), Score: self.Score(), ProductImg: self.ProductImg(), Quantity: self.Quantity() });
            $('#pro-edit').modal('hide');
        }).fail(function () {
            toastr.error('Edit Product Failed !');
        });
    }

    self.doDelete = function (item) {
        $.confirm({
            text: "Are you very sure to delete product " + item.Name + " ?",
            confirm: function (button) {
                $.ajax({
                    type: "DELETE",
                    url: "/api/AdminProduct/DeleteProduct/" + item.PId,
                    success: function (data) {
                        self.Products.remove(item);
                        toastr.success("Delete Product Successfully !");
                    },
                    error: function (error) {
                        toastr.error("Delete Product Failed !");
                    }
                });
            },
            confirmButton: "Yes",
            cancelButton: "No"
        });
    }

    self.doNext = function () {
        if (self.IsNext()) {
            var page = self.CurrentPage();
            page++;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#pro-list'), -100);
        }
    }

    self.doPrevious = function () {
        if (self.IsPrevious()) {
            var page = self.CurrentPage() - 1;
            self.CurrentPage(page);
            load(page, self.SearchString);
            if (page == 1) {
                self.IsPrevious(false)
            } else {
                self.IsPrevious(true);
            }
            $.replaceUrl(page, self.SearchString());
            App.scrollTo($('#pro-list'), -100);
        }
    }
}

var load = function (id, searchString) {
    viewModel.Loaded(false);
    viewModel.Products.removeAll();
    $.ajax({
        url: '/api/AdminProduct/GetProducts/' + id,
        type: 'GET',
        data: { value: searchString },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items.length === 11) {
            items.pop();
            viewModel.IsNext(true);
        } else {
            viewModel.IsNext(false);
        }
        $.each(items, function (idx, item) {
            viewModel.Products.push(new zombies.Product(item));
        });
        viewModel.Loaded(true);
    }).error(function () {
        toastr.error('error');
    })
};

ko.bindingHandlers.fileUpload = {
    init: function (element, valueAccessor) {
        $(element).after('<div class="progress" style="display: none; width: 50%"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            property = ko.utils.unwrapObservable(options.property),
            url = ko.utils.unwrapObservable(options.url);

        if (property && url) {
            $(element.form).change(function () {
                if (element.files.length)
                    var pre = $('#prethum');
                $.loadPreviewImg(element, pre);
            });
            $(element.form).submit(function () {
                if ($(element.form).valid() && element.files.length) {
                    var $this = $(element),
                        filename = $this.val();
                    var time = new Date($.now());
                    var fname = time.getTime() + $(element).prop("files")[0].name;
                    viewModel.ProductImg("..\\Advertise\\ProductImg\\" + fname);
                    //console.log(viewModel.ProductImg());
                    // this uses jquery.form.js plugin
                    $(element.form).ajaxSubmit({
                        url: url,
                        type: "POST",
                        dataType: "json",
                        data: { fname: fname },
                        headers: { "Content-Disposition": "attachment; filename=" + "aaaa" },
                        beforeSubmit: function () {
                            $(".progress").show();
                            $(".progressError").hide();
                            $(".bar").width("0%")
                            $(".percent").html("0%");
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + "%";
                            $(".bar").width(percentVal)
                            $(".percent").html(percentVal);
                        },
                        success: function (data) {
                            $(".progress").hide();
                            $(".progressError").hide();
                            // set viewModel property to IconPath
                            //bindingContext.$data[property](data);
                            viewModel.doEdit();
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $(".progress").hide();
                            $("div.progressError").html(jqXHR.responseText);
                        }
                    });
                }
                else {
                    viewModel.doEdit();
                }
                return false;
            });
        }
    }
}

var viewModel;
$(document).ready(function () {

    viewModel = new zombies.ListProduct();

    ko.applyBindings(viewModel, document.getElementById("admin_content"));

    var pageUrl = $.getUrlVars("page");
    var searchStringUrl = $.getUrlVars("searchString");
    if (typeof pageUrl === 'undefined' || !isFinite(String(pageUrl))) {
        viewModel.CurrentPage(1);
    } else {
        viewModel.CurrentPage(pageUrl);
    }
    if (typeof searchStringUrl === 'undefined') {
        viewModel.SearchString("");
    } else {
        viewModel.SearchString(searchStringUrl);
    }
    if (pageUrl > 1) viewModel.IsPrevious(true);
    load(viewModel.CurrentPage(), viewModel.SearchString());
});
